// pages/index/index.js
const app = getApp()
//初始化数据库
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls:['https://media.citymiai.com/images/TCYJOjMceQYqyAnUe5tKfEgT2F3VjP6t9D7UY0jK.png-normal',
    'https://media.citymiai.com/images/ae12I4hcDrI0W5JqJu4eRzYUIcoyLiUQZKNc3ofY.png-normal'
  ],
  listData: [],
  current : 'links',
  //活动
  showActivityDialog: false,
    activityForm: {
      title: '',
      time: '',
      description: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
   this.getListData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 跳转到活动中心
  goToActivities() {
    wx.navigateTo({
      url: '/pages/activities/activities'
    });
  },
  // 显示发起活动弹窗
  showActivityDialog() {
    this.setData({
      showActivityDialog: true
    });
  },
  // 隐藏弹窗
  hideActivityDialog() {
    this.setData({
      showActivityDialog: false
    });
  },

  // 表单输入处理
  handleActivityTitle(e) {
    this.setData({
      'activityForm.title': e.detail.value
    });
  },
  
  handleActivityTime(e) {
    this.setData({
      'activityForm.time': e.detail.value
    });
  },
  handleActivityDesc(e) {
    this.setData({
      'activityForm.description': e.detail.value
    });
  },

  // 提交活动
  submitActivity() {
    const { title, time, description } = this.data.activityForm;
    if (!title || !time || !description) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
    // 调用云函数提交活动
    wx.cloud.callFunction({
      name: 'createActivity',
      data: {
        title,
        time,
        description,
        creator: app.globalData.userInfo.nickName,
        participants: []
      },
      success: () => {
        wx.showToast({
          title: '活动创建成功'
        });
        this.hideActivityDialog();
      },
      fail: () => {
        wx.showToast({
          title: '创建失败',
          icon: 'none'
        });
      }
    });
  },

  handleLinks(ev){
    let id = ev.currentTarget.dataset.id;
    //console.log("点赞的id是"+ ev.currentTarget.dataset.id)
    wx.cloud.callFunction({
      name: 'update',
      data:{
        collection: 'users',
        doc: id,
        data: "{links: _.inc(1) }"
      }
    }).then((res)=>{
     let updated=res.result.stats.updated;
     if(updated){
       let cloneListDate = [...this.data.listData];
       for(let i=0;i<cloneListDate.length;i++){
         if(cloneListDate[i]._id == id){
           cloneListDate[i].links++;
         }
       }
       this.setData({
        listData: cloneListDate
       });
     }
    });
  },
  handleCurrent(ev){
    let current = ev.target.dataset.current;
    if(current == this.data.current){
      return false;
    }
    this.setData({
      current
    },()=>{
      this.getListData();
    }); 
  },
  getListData(){
    db.collection('users').field({
      userPhoto: true,
      nickName: true,
      links: true
    })
    .orderBy(this.data.current,'desc')
    .get().then((res)=>{
      console.log(res)
      this.setData({
        listData: res.data
      });
    });
  },
  handleDetail(ev){
    let id = ev.target.dataset.id;
    wx.navigateTo({
      url: '/pages/detail/detail?userId='+id,
    })
  },
  handleAddFriend(ev){
    let id = ev.currentTarget.dataset.id;
    if(app.userInfo._id){
      db.collection('favorites').where({
        userId: id
      }).get().then((res)=>{
        if( res.data.length){  // 更新
          if( res.data[0].list.includes(app.userInfo._id) ){ // 已经收藏
              wx.showToast({
                title: '已经收藏',
              })
          }else{
            wx.cloud.callFunction({
              name:'update',
              data:{
                collection: 'favorites',
                where:{
                  userId: id
                },
                data:`{list : _.unshift('${app.userInfo._id}')}`
              }
            }).then(()=>{
              wx.showToast({
                title: '申请成功',
              })
            });
          }
        }else{    // 添加
          db.collection('favorites').add({
            data:{
              userId: id,
              list: [app.userInfo._id]
            }
          }).then((res)=>{
            wx.showToast({
              title: '收藏成功',
            })
          })
        }
      });
    }else{
      wx.showToast({
        title: '请先登录',
        duration:2000,
        icon:'none',
        success:()=>{
          setTimeout(()=>{
            wx.switchTab({
              url: '/pages/user/user',
            })
          },2000);
        }
      })
    }
  }
})